<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>分类管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加分类" center show-icon type="warning" :closable="false">
  </el-alert>
      <el-form :model="addForm" :rules="addFormRule" ref="addFormRef">
        <el-form-item label="分类名称:" label-width="100px" prop="categoryname">
          <el-input v-model="addForm.categoryname"></el-input>
        </el-form-item>
        <el-form-item label-width="100px" label="父级分类:">
          <el-cascader
          v-model="selectedKeys"
          :options="addCateList"
          :props="{ expandTrigger: 'hover' , value: '_id' , label : 'categoryname' , checkStrictly: true  }"
          clearable
          @change="selectChange" style="width: 100%"></el-cascader>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="addCate" class="elbtn">添加</el-button>
    </el-card>
  </div>
</template>

<script>
import {mapState, mapActions} from 'vuex'
export default {
  data(){
    return{
      addForm:{
        categoryname:'',
        cate_pid:0,
        cate_level:0
      },
      selectedKeys:[],
      addFormRule:{
        categoryname:[{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      }
    }
  },
  created(){
    this.getCate()
  },
  methods:{
    ...mapActions('cateAbout',['getCateNoPage','addCateData']),
    getCate(){
      this.getCateNoPage()
    },
    selectChange(){
      this.addForm.cate_level = this.selectedKeys.length
      if (this.selectedKeys.length){
        this.addForm.cate_pid = this.selectedKeys[this.selectedKeys.length-1]
      }else{
        this.addForm.cate_pid = 0
      }
    },
    addCate(){
      this.$refs.addFormRef.validate(valid=>{
        if (valid){
          this.addCateData(this.addForm)
          this.selectedKeys = []
          this.$refs.addFormRef.resetFields()
          this.$router.push('/cate')
          this.getCate()
        }
      })
    }
  },
  computed:{
    ...mapState('cateAbout',['addCateList'])
  }
}
</script>

<style scoped>
  .el-alert{
    margin-bottom: 20px;
  }
  .elbtn{
    margin-left: 550px;
  }
</style>